package com.killer.es.service.impl;

import com.killer.es.entity.dto.EsOrderDTO;
import com.killer.es.service.EsOrderService;
import lombok.SneakyThrows;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class EsOrderServiceImpl implements EsOrderService {



    @Autowired
    private RestHighLevelClient esClient;


    /***
     * 使用search_after 查询
     * @param esOrderDTO
     * @return
     */
    @SneakyThrows
    @Override
    public Map<String, Object> searchOrder(EsOrderDTO esOrderDTO) {
        Map<String, Object> map = new HashMap<>();
        SearchRequest searchRequest = new SearchRequest("es-order");
        //构建请求  设置查询条件  排序条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.from(0);
        sourceBuilder.size(esOrderDTO.getPageSize());
        //根据创建时间倒序
        sourceBuilder.sort("create_time", SortOrder.DESC);
        if(esOrderDTO.getSearchAfter() == null || esOrderDTO.getSearchAfter().length <=0){
            sourceBuilder.searchAfter(new Object[]{0L});
        }else {
            sourceBuilder.searchAfter(esOrderDTO.getSearchAfter());
        }
        searchRequest.source(sourceBuilder);

        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] searchHits = response.getHits().getHits();
        List<String> result = new ArrayList<>();
        int length = searchHits.length;
        for (int i = 0; i < length; i++) {
            result.add(searchHits[i].getSourceAsString());
            if (i == length - 1) {
                map.put("searchAfters", searchHits[i].getSortValues());
            }
        }
        map.put("data", result);
        return map;
    }


}
